package com.yfh.study.manager.sockerServer;

import com.alibaba.fastjson.JSON;
import com.yfh.study.manager.entity.LinkMessage;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @ServerEndpoint("/games")连接的叫什么资源
 * 实现简单聊天功能
 *
 */
@Component
@ServerEndpoint("/chat")
public class WebsockerServer {
    /**
     * websocker的session
     */
    private Session session;
    /**
     * 保存websocket连接消息
     */
    private static CopyOnWriteArraySet<WebsockerServer> websokcets = new CopyOnWriteArraySet<>();

    //获取连接
    public Session getSession(){return this.session;}
    /**
     * 连接成功后调用的方法
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) throws IOException {
        System.out.println("连接成功");
        //反馈id
        session.getBasicRemote().sendText("myid:"+session.getId());
        //存到session集合中
        this.session=session;
        websokcets.add(this);
    }

    /**
     * 关闭后调用的方法
     */
    @OnClose
    public void onClose(){
        System.out.println("关闭成功");
        websokcets.remove(this);
    }

    /**
     *发送端发送消息接收到
     */
    @OnMessage
    public void onMessage(String message,Session session) throws IOException {
        System.out.println("消息接收成功："+message+session.getId());

        //群发
        LinkMessage linkMessage=new LinkMessage();
        linkMessage.setId(session.getId());
        linkMessage.setMessage(message);

        for (WebsockerServer websokcet : websokcets) {
            if (websokcet==this) {
                continue;
            }
            websokcet.getSession().getBasicRemote().sendText(JSON.toJSONString(linkMessage));
        }
        System.out.println("用户"+linkMessage.getId()+"发送成功");

    }

    @OnError
    public void onError(Session session,Throwable throwable){
        throwable.printStackTrace();
    }



}
